import { defineStore } from 'pinia'

export const useCartStore = defineStore({
  id: 'cart',
  state: () => {
    return {
      cartList: [], //购物车数据
      select: [], //选中商品的id
      orderList: [],
    }
  },
  getters: {
    isChecked() {
      return this.cartList.length && this.select.length === this.cartList.length
    },
    total() {
      const total = {
        price: 0,
        number: 0,
      }
      this.cartList.forEach((v) => {
        if (this.select.indexOf(v.id) > -1) {
          total.price += v.discountPrice * v.counter
          this.orderList.push({
            number: 1,
            id: v.courseId,
          })
        }
      })
      total.number = this.select.length
      return total
    },
  },
  actions: {
    // 存储购物车数据
    addCart(list) {
      list.forEach((v) => {
        v['check'] = true
        this.select.push(v.id)
      })
      this.cartList = list
    },
    all() {
      this.select = this.cartList.map((v) => {
        v['check'] = true
        return v.id
      })
    },
    unAll() {
      this.cartList.forEach((v) => {
        v['check'] = false
      })
      this.select = []
    },
    // 单选
    itemChecked(index) {
      // 当前点击的课程id值
      const id = this.cartList[index].id
      const idx = this.select.indexOf(id)
      if (idx > -1) {
        this.cartList[index].check = false
        this.select.splice(idx, 1)
      } else {
        this.cartList[index].check = true
        this.select.push(id)
      }
    },
  },
})
